﻿using System.Collections.Generic;
using System.Linq;

namespace JJYYCore
{
    public class ObjectPoolManager
    {
        private List<PoolResContainer> pool = new List<PoolResContainer>();
        private ObjectPoolResFactoryBase factory;

        public IPoolRes Get(string id)
        {
            if (pool.Any(res => res.id == id))
            {
                var selectedPool = pool.FirstOrDefault(res => res.id == id);
                return GetIdleRes(selectedPool);
            }
            else{
                var createdPool = new PoolResContainer()
                {
                    id = id,
                    collectedRes = new List<IPoolRes>()
                };

                pool.Add(createdPool);
                return CreateAsset(id);
            }
        }

        public void Collect(IPoolRes res)
        {
            res.Collect();

            if (pool.Any(selection => selection.id == res.ID))
            {
                var selectedPool = pool.FirstOrDefault(selected => selected.id == res.ID);
                selectedPool.collectedRes.Add(res);
            }
            else{
                var createdPool = new PoolResContainer()
                {
                    id = res.ID,
                    collectedRes = new List<IPoolRes>()
                };

                createdPool.collectedRes.Add(res);
                pool.Add(createdPool);
            }
        }

        private IPoolRes GetIdleRes(PoolResContainer container)
        {
            var selection = container.collectedRes;

            for (int i = 0; i < selection.Count; i++)
            {
                var res = selection[i];
                if(!res.Active){
                    res.LoadFromPool();
                    return res;
                }
            }

            return CreateAsset(container.id);
        }

        private IPoolRes CreateAsset(string id)
        {
            var created = factory.Get(id);
            created.LoadFromPool();

            return created;
        }

        public ObjectPoolManager(ObjectPoolResFactoryBase resFactory)
        {
            factory = resFactory;
        }
    }

    public struct PoolResContainer
    {
        public string id;
        public List<IPoolRes> collectedRes;
    }
}